﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MallInteractiveMap.CMSWebClient.Common;
using MallInteractiveMap.CMSWebClient.Presenter;
using MallInteractiveMap.DTO;
using MallInteractiveMap.Language;

namespace MallInteractiveMap.CMSWebClient.BasicView
{
    public partial class Map : BasePage
    {
        private MapPresenter _presenter;
        protected void Page_Load(object sender, EventArgs e)
        {
            _presenter = new MapPresenter();
            if (!IsPostBack)
            {
                PrepareView();
            }
        }

        public int Id
        {
            get { return Request.QueryString["Id"] != null ? Convert.ToInt32(Request.QueryString["Id"]) : 0; }
        }

        private void PrepareView()
        {
            if (Id > 0)
            {
                DTOMap map = _presenter.GetMaps(Id).FirstOrDefault();
                PopulateControls(map);
            }

        }
        private void PopulateControls(DTOMap map)
        {
            TitleTextBox.Text = map.Title;
            ShopCount.Text = map.ShopCount.ToString();
            Description.Text = map.Description;
        }
        private DTOMap PopulateObject()
        {
            DTOMap map = new DTOMap();
            map.Title = TitleTextBox.Text;
            map.ShopCount = Convert.ToInt32( ShopCount.Text);
            map.Description = Description.Text;
            map.LastUpdated = DateTime.Now;
            map.IsNew = Id <= 0;
            map.Id = Id;
            return map;
        }

        protected void Save_Click(object sender, EventArgs e)
        {
            DTOMap map = PopulateObject();
            if (_presenter.SetData(map))
            {
                Response.Redirect("~/BasicView/MapDetail.aspx");
            }
            else
            {
                ShowMessage(LanguageLoader.GetText("FAILED_OPERATION_MESSAGE"), LanguageLoader.GetText("FAILED"));
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            SetLanguageAndResource();
        }

        private void SetLanguageAndResource()
        {
            TitleLable.Text = LanguageLoader.GetText("TITLE");
            ShopCountLabel.Text = LanguageLoader.GetText("SHOP_COUNT");
            DescriptionLable.Text = LanguageLoader.GetText("DESCRIPTION");
            SaveMap.Text = LanguageLoader.GetText("SAVE");
        }
    }
}